"""
富途交易接口模块 - 封装富途OpenAPI的交易功能
注意：需要安装 futu-api 包才能使用实际交易功能
"""

import logging
from typing import Optional, Dict, Any, List
from datetime import datetime
import requests
import json

# 🔥 修复：在模块级别导入富途API
try:
    from futu import *
    FUTU_AVAILABLE = True
except ImportError:
    FUTU_AVAILABLE = False


class FutuTrader:
    """富途交易接口封装类"""
    
    def __init__(self, config_manager):
        """
        初始化富途交易接口
        Args:
            config_manager: 配置管理器
        """
        self.config_manager = config_manager
        self.logger = logging.getLogger(__name__)
        
        # 交易连接状态
        self.is_connected = False
        self.trade_context = None
        
        # 真实交易模式（用户已确认承担风险）
        self.simulation_mode = False
        
        self.logger.info("富途交易接口初始化")
    
    def connect(self, host: str = "127.0.0.1", port: int = 11111) -> bool:
        """
        连接富途OpenAPI
        Args:
            host: 富途API服务地址
            port: 富途API服务端口
        Returns:
            连接是否成功
        """
        try:
            if self.simulation_mode:
                self.logger.info("⚠️ 模拟模式：富途API连接成功")
                self.is_connected = True
                return True
            
            # 真实交易模式：连接富途API
            if not FUTU_AVAILABLE:
                self.logger.error("❌ 富途API包未安装，请安装 futu-api")
                return False
            
            # 🔥 修复：根据当前选择的账户创建交易连接
            selected_broker = self.config_manager.get('trading.selected_broker', '')
            
            # 根据券商确定市场和券商类型
            if 'Moomoo US' in selected_broker or 'US' in selected_broker:
                filter_trdmarket = TrdMarket.US
                security_firm = SecurityFirm.FUTUINC
                self.logger.info(f"🔧 创建交易连接: 美股市场 (Moomoo US)")
            elif 'FUTU HK' in selected_broker or 'HK' in selected_broker:
                filter_trdmarket = TrdMarket.HK
                security_firm = SecurityFirm.FUTUSECURITIES
                self.logger.info(f"🔧 创建交易连接: 港股市场 (FUTU HK)")
            else:
                # 默认美股
                filter_trdmarket = TrdMarket.US
                security_firm = SecurityFirm.FUTUINC
                self.logger.warning(f"⚠️ 未知券商类型 '{selected_broker}'，默认使用美股市场")
            
            # 🔥 详细日志：记录交易连接参数（对比参考代码）
            self.logger.info(f"🔍 OpenSecTradeContext参数对比:")
            self.logger.info(f"   filter_trdmarket: {filter_trdmarket} (参考代码: TrdMarket.US)")
            self.logger.info(f"   host: {host} (参考代码: '127.0.0.1')")
            self.logger.info(f"   port: {port} (参考代码: 11111)")
            self.logger.info(f"   security_firm: {security_firm} (参考代码: SecurityFirm.FUTUINC)")
            
            self.trade_context = OpenSecTradeContext(
                filter_trdmarket=filter_trdmarket,
                host=host, 
                port=port, 
                security_firm=security_firm
            )
            
            # 测试连接：获取账户列表
            ret, data = self.trade_context.get_acc_list()
            
            if ret == RET_OK:
                self.logger.info(f"✅ 富途API连接成功")
                self.logger.info(f"📋 可用账户数量: {len(data)} 个")
                self.is_connected = True
                return True
            else:
                self.logger.error(f"❌ 富途API连接失败: {data}")
                return False
            
        except ImportError:
            self.logger.error("❌ 富途API包未安装，请安装 futu-api")
            return False
        except Exception as e:
            self.logger.error(f"❌ 连接富途API失败: {e}")
            return False
    
    def disconnect(self):
        """断开连接"""
        try:
            if self.trade_context:
                self.trade_context.close()
                self.logger.info("富途API连接已关闭")
            
            self.is_connected = False
            self.trade_context = None
            
        except Exception as e:
            self.logger.error(f"断开连接失败: {e}")
    
    def buy_stock(self, code: str, quantity: int, price: float = None, trading_password: str = None) -> Dict[str, Any]:
        """
        买入股票
        Args:
            code: 股票代码 (如: US.AAPL)
            quantity: 买入数量
            price: 买入价格，None为市价
        Returns:
            交易结果
        """
        try:
            if not self.is_connected:
                return {"success": False, "message": "未连接到交易接口"}
            
            # 获取配置 - 🔥 修复：优先使用传入的交易密码
            password = trading_password or self.config_manager.get('trading.password', '')
            acc_id = self.config_manager.get('trading.selected_acc_id', '')
            selected_broker = self.config_manager.get('trading.selected_broker', '')
            
            # 🔥 详细日志：显示当前使用的账户信息
            self.logger.info(f"🔧 买入交易配置: 券商={selected_broker}, 账户ID={acc_id}")
            self.logger.info(f"🔧 密码来源: {'传入参数' if trading_password else '配置文件'}")
            
            if not password:
                return {"success": False, "message": "未设置交易密码"}
            if not acc_id:
                return {"success": False, "message": "未选择交易账户"}
            
            order_type = "市价买入" if price is None else f"限价买入 ${price}"
            
            if self.simulation_mode:
                # 模拟交易
                result = {
                    "success": True,
                    "message": f"模拟交易：{order_type} {code} {quantity}股",
                    "order_id": f"SIM_{datetime.now().strftime('%Y%m%d%H%M%S')}",
                    "code": code,
                    "quantity": quantity,
                    "price": price,
                    "order_type": "BUY",
                    "timestamp": datetime.now().isoformat()
                }
                
                self.logger.info(f"✅ {result['message']}")
                return result
            
            # 真实交易：调用富途API
            if not FUTU_AVAILABLE:
                return {"success": False, "message": "富途API包未安装"}
            
            self.logger.info(f"🔓 解锁交易权限...")
            
            # 🔥 详细日志：解锁参数对比
            self.logger.info(f"🔍 [买入]unlock_trade参数对比:")
            self.logger.info(f"   password: {'*' * len(password)} (长度: {len(password)}) (参考代码: '020016', 长度: 6)")
            self.logger.info(f"   password实际值: '{password}' (⚠️仅调试显示，正式版应隐藏)")
            self.logger.info(f"   acc_id: {acc_id} (参考代码: 283445330140129296)")
            self.logger.info(f"   selected_broker: {selected_broker} (参考代码: Moomoo US)")
            
            # 解锁交易
            ret, unlock_data = self.trade_context.unlock_trade(password)
            
            # 🔥 详细日志：解锁结果
            self.logger.info(f"🔍 [买入]unlock_trade结果:")
            self.logger.info(f"   ret: {ret} (期望: {RET_OK})")
            self.logger.info(f"   unlock_data: {unlock_data}")
            
            if ret != RET_OK:
                return {"success": False, "message": f"解锁交易失败: {unlock_data}"}
            
            self.logger.info(f"✅ 解锁成功!")
            self.logger.info(f"📋 下单参数: {code}, 数量: {quantity}, 价格: {price}, 账户: {acc_id}")
            
            # 🔥 完全照搬测试代码 buy_nvda_limit_order.py 的逻辑
            self.logger.info(f"🎯 完全照搬测试代码逻辑进行下单...")
            
            # 测试代码参数：
            # price=limit_price, qty=qty, code=stock_code, trd_side=TrdSide.BUY, order_type=OrderType.NORMAL, trd_env=TrdEnv.REAL, acc_id=target_acc_id
            
            if price is None:
                # 市价单，但按测试代码传入一个价格
                actual_price = 100.0  # 测试代码用的是 limit_price，我们用100
                order_type = OrderType.MARKET
                self.logger.info(f"📋 市价买入，按测试代码逻辑传入价格: ${actual_price}")
            else:
                # 限价单，完全按测试代码
                actual_price = price
                order_type = OrderType.NORMAL
                self.logger.info(f"📋 限价买入，按测试代码逻辑传入价格: ${actual_price}")
            
            # 🔥 修复：使用正确的计算数量，确保为float类型
            actual_qty = float(quantity)  # API要求float类型
            self.logger.info(f"📋 使用计算出的正确数量: {actual_qty}股 (传入参数: {quantity})")
            
            # 🔥 详细参数对比和解释
            self.logger.info(f"🔍 API参数完全对比:")
            self.logger.info(f"   💰 price(限价价格): {actual_price} (type: {type(actual_price)}) - 限价单的具体价格")
            self.logger.info(f"   📊 qty(订单数量): {actual_qty} (type: {type(actual_qty)}) - API要求float类型")
            self.logger.info(f"   📈 code(股票代码): '{code}' (type: {type(code)})")
            self.logger.info(f"   🔄 trd_side(交易方向): {TrdSide.BUY}")
            self.logger.info(f"   📋 order_type(订单类型): {order_type} - {'限价单' if order_type == OrderType.NORMAL else '市价单'}")
            self.logger.info(f"   🌐 trd_env(交易环境): {TrdEnv.REAL}")
            self.logger.info(f"   🏦 acc_id(账户ID): {int(acc_id)} (type: {type(int(acc_id))})")
            
            # 🔥 关键修复：价格精度问题！价格必须精确到0.01美元
            actual_price = round(actual_price, 2)  # 精确到小数点后2位
            self.logger.info(f"💰 价格精度修复: {actual_price} -> {actual_price} (精确到0.01美元)")
            
            # 完全照搬测试代码的place_order调用
            self.logger.info(f"🚀 完全按测试代码place_order调用...")
            ret, order_data = self.trade_context.place_order(
                price=actual_price,
                qty=actual_qty,
                code=code,
                trd_side=TrdSide.BUY,
                order_type=order_type,
                trd_env=TrdEnv.REAL,
                acc_id=int(acc_id)
            )
            
            # 🔥 详细日志：place_order调用结果
            self.logger.info(f"🔍 [买入]place_order结果:")
            self.logger.info(f"   ret: {ret} (期望: {RET_OK})")
            self.logger.info(f"   order_data: {order_data}")
            
            if ret == RET_OK:
                order_info = order_data.iloc[0]
                order_id = order_info['order_id']
                
                return {
                    "success": True,
                    "message": f"买入订单提交成功 - {order_type}",
                    "order_id": order_id,
                    "code": code,
                    "quantity": quantity,
                    "price": price,
                    "order_type": "BUY",
                    "timestamp": datetime.now().isoformat(),
                    "acc_id": acc_id
                }
            else:
                return {"success": False, "message": f"下单失败: {order_data}"}
            
        except Exception as e:
            self.logger.error(f"买入股票失败: {e}")
            return {"success": False, "message": f"交易异常: {e}"}
    
    def sell_stock(self, code: str, quantity: int, price: float = None, trading_password: str = None) -> Dict[str, Any]:
        """
        卖出股票
        Args:
            code: 股票代码 (如: US.AAPL)
            quantity: 卖出数量
            price: 卖出价格，None为市价
        Returns:
            交易结果
        """
        try:
            if not self.is_connected:
                return {"success": False, "message": "未连接到交易接口"}
            
            # 获取配置 - 🔥 修复：优先使用传入的交易密码
            password = trading_password or self.config_manager.get('trading.password', '')
            acc_id = self.config_manager.get('trading.selected_acc_id', '')
            selected_broker = self.config_manager.get('trading.selected_broker', '')
            
            # 🔥 详细日志：显示当前使用的账户信息
            self.logger.info(f"🔧 卖出交易配置: 券商={selected_broker}, 账户ID={acc_id}")
            self.logger.info(f"🔧 密码来源: {'传入参数' if trading_password else '配置文件'}")
            
            if not password:
                return {"success": False, "message": "未设置交易密码"}
            if not acc_id:
                return {"success": False, "message": "未选择交易账户"}
            
            order_type = "市价卖出" if price is None else f"限价卖出 ${price}"
            
            if self.simulation_mode:
                # 模拟交易
                result = {
                    "success": True,
                    "message": f"模拟交易：{order_type} {code} {quantity}股",
                    "order_id": f"SIM_{datetime.now().strftime('%Y%m%d%H%M%S')}",
                    "code": code,
                    "quantity": quantity,
                    "price": price,
                    "order_type": "SELL",
                    "timestamp": datetime.now().isoformat()
                }
                
                self.logger.info(f"✅ {result['message']}")
                return result
            
            # 真实交易：调用富途API
            if not FUTU_AVAILABLE:
                return {"success": False, "message": "富途API包未安装"}
            
            self.logger.info(f"🔓 解锁交易权限...")
            
            # 🔥 详细日志：解锁参数对比
            self.logger.info(f"🔍 [卖出]unlock_trade参数对比:")
            self.logger.info(f"   password: {'*' * len(password)} (长度: {len(password)}) (参考代码: '020016', 长度: 6)")
            self.logger.info(f"   password实际值: '{password}' (⚠️仅调试显示，正式版应隐藏)")
            self.logger.info(f"   acc_id: {acc_id} (参考代码: 283445330140129296)")
            self.logger.info(f"   selected_broker: {selected_broker} (参考代码: Moomoo US)")
            
            # 解锁交易
            ret, unlock_data = self.trade_context.unlock_trade(password)
            
            # 🔥 详细日志：解锁结果
            self.logger.info(f"🔍 [卖出]unlock_trade结果:")
            self.logger.info(f"   ret: {ret} (期望: {RET_OK})")
            self.logger.info(f"   unlock_data: {unlock_data}")
            
            if ret != RET_OK:
                return {"success": False, "message": f"解锁交易失败: {unlock_data}"}
            
            self.logger.info(f"✅ 解锁成功!")
            self.logger.info(f"📋 下单参数: {code}, 数量: {quantity}, 价格: {price}, 账户: {acc_id}")
            
            # 🔥 完全照搬测试代码 buy_nvda_limit_order.py 的逻辑 (改为卖出)
            self.logger.info(f"🎯 完全照搬测试代码逻辑进行卖出...")
            
            if price is None:
                # 市价卖出，按测试代码传入一个价格
                actual_price = 100.0  # 测试代码用的是 limit_price，我们用100
                order_type = OrderType.MARKET
                self.logger.info(f"📋 市价卖出，按测试代码逻辑传入价格: ${actual_price}")
            else:
                # 限价卖出，完全按测试代码
                actual_price = price
                order_type = OrderType.NORMAL
                self.logger.info(f"📋 限价卖出，按测试代码逻辑传入价格: ${actual_price}")
            
            # 🔥 修复：使用正确的计算数量，确保为float类型
            actual_qty = float(quantity)  # API要求float类型
            self.logger.info(f"📋 使用计算出的正确数量: {actual_qty}股 (传入参数: {quantity})")
            
            # 🔥 详细参数对比测试代码 (卖出版本)
            self.logger.info(f"🔍 卖出参数完全对比测试代码:")
            self.logger.info(f"   测试代码: price=167.8 (float) | 当前: price={actual_price} (type: {type(actual_price)})")
            self.logger.info(f"   API要求: qty=float类型     | 当前: qty={actual_qty} (type: {type(actual_qty)})")
            self.logger.info(f"   测试代码: code='US.NVDA'    | 当前: code='{code}' (type: {type(code)})")
            self.logger.info(f"   测试代码: trd_side=BUY      | 当前: trd_side={TrdSide.SELL} (改为卖出)")
            self.logger.info(f"   测试代码: order_type=NORMAL | 当前: order_type={order_type}")
            self.logger.info(f"   测试代码: trd_env=REAL      | 当前: trd_env={TrdEnv.REAL}")
            self.logger.info(f"   测试代码: acc_id=283445330140129296 | 当前: acc_id={int(acc_id)} (type: {type(int(acc_id))})")
            
            # 🔥 关键修复：价格精度问题！价格必须精确到0.01美元
            actual_price = round(actual_price, 2)  # 精确到小数点后2位
            self.logger.info(f"💰 价格精度修复: {actual_price} -> {actual_price} (精确到0.01美元)")
            
            # 完全照搬测试代码的place_order调用 (只改TrdSide为SELL)
            self.logger.info(f"🚀 完全按测试代码place_order调用(卖出)...")
            ret, order_data = self.trade_context.place_order(
                price=actual_price,
                qty=actual_qty,
                code=code,
                trd_side=TrdSide.SELL,  # 卖出
                order_type=order_type,
                trd_env=TrdEnv.REAL,
                acc_id=int(acc_id)
            )
            
            # 🔥 详细日志：place_order调用结果
            self.logger.info(f"🔍 [卖出]place_order结果:")
            self.logger.info(f"   ret: {ret} (期望: {RET_OK})")
            self.logger.info(f"   order_data: {order_data}")
            
            if ret == RET_OK:
                order_info = order_data.iloc[0]
                order_id = order_info['order_id']
                
                return {
                    "success": True,
                    "message": f"卖出订单提交成功 - {order_type}",
                    "order_id": order_id,
                    "code": code,
                    "quantity": quantity,
                    "price": price,
                    "order_type": "SELL",
                    "timestamp": datetime.now().isoformat(),
                    "acc_id": acc_id
                }
            else:
                return {"success": False, "message": f"下单失败: {order_data}"}
            
        except Exception as e:
            self.logger.error(f"卖出股票失败: {e}")
            return {"success": False, "message": f"交易异常: {e}"}
    
    def get_account_info(self) -> Dict[str, Any]:
        """获取账户信息 - 🔥 修复：实现真实API调用"""
        try:
            if not self.is_connected:
                return {"success": False, "message": "未连接到交易接口"}
            
            if self.simulation_mode:
                # 模拟账户信息
                return {
                    "success": True,
                    "account_id": "模拟账户",
                    "total_assets": 100000.0,
                    "available_cash": 50000.0,
                    "market_value": 50000.0,
                    "message": "模拟账户信息"
                }
            
            # 🔥 修复：实现真实API调用
            if not FUTU_AVAILABLE:
                return {"success": False, "message": "富途API未安装"}
                
            from futu import OpenSecTradeContext, TrdEnv, RET_OK, SecurityFirm, TrdMarket
            
            # 🔥 使用与get_positions相同的连接配置
            trd_ctx = OpenSecTradeContext(
                filter_trdmarket=TrdMarket.US,
                host='127.0.0.1', 
                port=11111,
                security_firm=SecurityFirm.FUTUINC
            )
            
            try:
                # 获取账户ID
                acc_id = self.config_manager.get('trading.selected_acc_id', '')
                if not acc_id:
                    ret, acc_data = trd_ctx.get_acc_list()
                    if ret == RET_OK and not acc_data.empty:
                        acc_id = int(acc_data.iloc[0]['acc_id'])
                    else:
                        raise Exception("无法获取账户列表")
                else:
                    acc_id = int(acc_id)
                
                # 查询账户资金信息
                self.logger.info("🔍 调用 accinfo_query API...")
                ret, data = trd_ctx.accinfo_query(trd_env=TrdEnv.REAL, acc_id=acc_id)
                
                if ret != RET_OK:
                    raise Exception(f"查询账户信息失败: {data}")
                
                if data.empty:
                    raise Exception("账户信息为空")
                
                row = data.iloc[0]
                
                # 🔥 根据市场类型判断是否需要汇率转换
                total_assets_hkd = float(row['total_assets'])
                available_funds_hkd = float(row['avl_withdrawal_cash'])
                
                # 美股账户：港币转换为美元
                hkd_to_usd_rate = self.get_hkd_to_usd_rate()
                total_assets = total_assets_hkd * hkd_to_usd_rate
                available_funds = available_funds_hkd * hkd_to_usd_rate
                
                account_info = {
                    "success": True,
                    "account_id": str(acc_id),
                    "total_assets": total_assets,
                    "available_cash": available_funds,
                    "market_value": total_assets - available_funds,  # 市值 = 总资产 - 可用资金
                    "currency": "USD",
                    "original_hkd_assets": total_assets_hkd,
                    "conversion_rate": hkd_to_usd_rate,
                    "message": f"账户信息获取成功 (${total_assets:,.2f} USD)"
                }
                
                self.logger.info(f"✅ 账户信息: 总资产=${total_assets:,.2f} USD, 可用资金=${available_funds:,.2f} USD")
                return account_info
                
            finally:
                trd_ctx.close()
            
        except Exception as e:
            self.logger.error(f"获取账户信息失败: {e}")
            return {"success": False, "message": f"查询异常: {e}"}
    
    def get_positions(self) -> List[Dict[str, Any]]:
        """获取持仓信息 - 🔥 修复：使用测试验证的正确API调用方式"""
        try:
            if not self.is_connected:
                self.logger.warning("未连接到富途交易接口，尝试连接...")
                if not self.connect():
                    return []
            
            # 🔥 实现真实的持仓数据获取
            self.logger.info("🔗 正在获取富途账户真实持仓数据...")
            
            if not FUTU_AVAILABLE:
                self.logger.error("富途API未安装，无法获取真实持仓")
                return []
                
            from futu import OpenSecTradeContext, TrdEnv, RET_OK, SecurityFirm, TrdMarket
            
            # 🔥 修复：使用测试验证成功的连接参数
            trd_ctx = OpenSecTradeContext(
                filter_trdmarket=TrdMarket.US,  # 🔥 修复：指定美股市场
                host='127.0.0.1', 
                port=11111,
                security_firm=SecurityFirm.FUTUINC  # 🔥 修复：使用正确的美股券商
            )
            
            try:
                # 获取账户ID
                acc_id = self.config_manager.get('trading.selected_acc_id', '')
                if not acc_id:
                    # 如果没有配置账户ID，获取第一个可用账户
                    ret, acc_data = trd_ctx.get_acc_list()
                    if ret == RET_OK and not acc_data.empty:
                        acc_id = int(acc_data.iloc[0]['acc_id'])
                        self.logger.info(f"🎯 使用第一个可用账户: {acc_id}")
                    else:
                        raise Exception("无法获取账户列表")
                else:
                    acc_id = int(acc_id)
                    self.logger.info(f"🎯 使用配置的账户: {acc_id}")
                
                # 🔥 修复：使用测试验证成功的API调用方式
                self.logger.info("🔍 调用 position_list_query API...")
                ret, position_data = trd_ctx.position_list_query(
                    code='',                           # 获取所有持仓
                    position_market=TrdMarket.NONE,    # 全部市场
                    pl_ratio_min=None,                 
                    pl_ratio_max=None,                 
                    trd_env=TrdEnv.REAL,               # 真实环境
                    acc_id=acc_id,                     # 🔥 修复：指定账户ID
                    acc_index=0,                       
                    refresh_cache=True                 # 刷新缓存获取最新数据
                )
                
                self.logger.info(f"🔍 API调用结果: ret={ret}")
                
                if ret != RET_OK:
                    raise Exception(f"查询持仓失败: {position_data}")
                
                positions = []
                if not position_data.empty:
                    self.logger.info(f"✅ 获取到 {len(position_data)} 个持仓")
                    self.logger.info(f"📊 返回数据字段: {list(position_data.columns)}")
                    
                    for index, row in position_data.iterrows():
                        position_info = {
                            "code": str(row['code']),
                            "name": str(row['stock_name']),
                            "quantity": float(row['qty']),
                            "cost_price": float(row['cost_price']),
                            "current_price": float(row['nominal_price']),  # 🔥 修复：使用正确的字段名
                            "market_value": float(row['market_val']),
                            "profit_loss": float(row['pl_val']),
                            "profit_loss_ratio": float(row['pl_ratio']),
                            "position_side": str(row['position_side']),
                            "currency": str(row['currency']) if 'currency' in row else 'USD'
                        }
                        positions.append(position_info)
                        
                    self.logger.info("📋 持仓详情:")
                    for pos in positions:
                        self.logger.info(f"   📊 {pos['code']} ({pos['name']})")
                        self.logger.info(f"      💰 持有: {pos['quantity']}股, 市价: ${pos['current_price']:.2f}")
                        self.logger.info(f"      📈 市值: ${pos['market_value']:,.2f}, 盈亏: ${pos['profit_loss']:+,.2f} ({pos['profit_loss_ratio']:+.2%})")
                else:
                    self.logger.info("📊 当前无持仓")
                    
                return positions
                
            finally:
                trd_ctx.close()
            
        except Exception as e:
            self.logger.error(f"获取持仓信息失败: {e}")
            return []
    
    def get_stock_position_price(self, code: str) -> float:
        """获取特定股票的持仓面值价格（用于卖出）"""
        try:
            from futu import OpenSecTradeContext, TrdEnv, RET_OK, SecurityFirm, TrdMarket
            
            # 创建交易连接
            trd_ctx = OpenSecTradeContext(
                filter_trdmarket=TrdMarket.US,  # 根据需要调整市场
                host='127.0.0.1', 
                port=11111, 
                security_firm=SecurityFirm.FUTUSECURITIES
            )
            
            try:
                # 解锁交易权限
                password = self.config_manager.get('trading.password', '')
                if not password:
                    raise Exception("交易密码未配置")
                    
                ret, unlock_data = trd_ctx.unlock_trade(password)
                if ret != RET_OK:
                    raise Exception(f"交易解锁失败: {unlock_data}")
                
                # 查询持仓列表
                ret, position_data = trd_ctx.position_list_query(
                    trd_env=TrdEnv.REAL,  # 真实环境
                    refresh_cache=True    # 刷新缓存获取最新数据
                )
                
                if ret != RET_OK:
                    raise Exception(f"查询持仓失败: {position_data}")
                
                if position_data.empty:
                    raise Exception(f"没有找到股票 {code} 的持仓")
                
                # 查找指定股票的持仓
                stock_positions = position_data[position_data['code'] == code]
                if stock_positions.empty:
                    raise Exception(f"没有找到股票 {code} 的持仓")
                
                # 获取面值价格
                position = stock_positions.iloc[0]
                nominal_price = float(position['nominal_price'])
                
                self.logger.info(f"获取 {code} 持仓面值价格: ${nominal_price:.2f}")
                return nominal_price
                
            finally:
                trd_ctx.close()
                
        except Exception as e:
            self.logger.error(f"获取 {code} 持仓价格失败: {e}")
            # 返回一个默认值，避免程序崩溃
            return 0.0
    
    def cancel_order(self, order_id: str) -> Dict[str, Any]:
        """撤销订单"""
        try:
            if not self.is_connected:
                return {"success": False, "message": "未连接到交易接口"}
            
            if self.simulation_mode:
                return {
                    "success": True,
                    "message": f"模拟撤单成功：{order_id}",
                    "order_id": order_id
                }
            
            # 实际API调用
            # ... 省略实际代码
            
        except Exception as e:
            self.logger.error(f"撤销订单失败: {e}")
            return {"success": False, "message": f"撤单异常: {e}"}
    
    def set_simulation_mode(self, enabled: bool):
        """设置模拟交易模式"""
        self.simulation_mode = enabled
        mode_text = "模拟" if enabled else "实盘"
        self.logger.info(f"交易模式切换为: {mode_text}")
    
    def is_simulation_mode(self) -> bool:
        """是否为模拟交易模式"""
        return self.simulation_mode
    
    def validate_trading_config(self) -> bool:
        """验证交易配置"""
        password = self.config_manager.get('trading.password', '')
        if not password:
            self.logger.error("交易密码未设置")
            return False
        
        if not self.is_connected:
            self.logger.error("未连接到交易接口")
            return False
        
        return True
    
    def get_acc_list(self) -> List[Dict[str, Any]]:
        """
        获取所有券商的交易业务账户列表
        Returns:
            账户列表，包含acc_id、trd_env、acc_status等信息，资产已转换为美元
        """
        try:
            self.logger.info("🔄 获取所有券商账户列表...")
            return self.get_all_brokers_accounts()
            
        except ImportError:
            self.logger.error("❌ 富途API包未安装，请运行: pip install futu-api")
            return []
        except Exception as e:
            self.logger.error(f"获取账户列表失败: {e}")
            return []
    
    def get_account_funds(self, acc_id: str) -> Dict[str, float]:
        """
        获取指定账户的资金信息（已弃用，建议使用 get_account_funds_with_broker）
        Args:
            acc_id: 账户ID
        Returns:
            包含total_assets和available_funds的字典，默认返回港币（为了兼容性）
        """
        try:
            # 直接使用富途API获取资金信息
            from futu import OpenSecTradeContext, TrdEnv, RET_OK, SecurityFirm
            
            self.logger.warning(f"⚠️ 使用了旧版本的 get_account_funds 方法，建议使用 get_account_funds_with_broker")
            
            # 创建交易连接
            trd_ctx = OpenSecTradeContext(
                host='127.0.0.1', 
                port=11111, 
                security_firm=SecurityFirm.FUTUSECURITIES
            )
            
            try:
                # 查询账户资金信息
                ret, data = trd_ctx.accinfo_query(trd_env=TrdEnv.REAL, acc_id=int(acc_id))
                if ret == RET_OK and not data.empty:
                    row = data.iloc[0]
                    # 注意：这里返回的是港币原始数据，不进行汇率转换（保持兼容性）
                    return {
                        'total_assets': float(row['total_assets']),
                        'available_funds': float(row['avl_withdrawal_cash']),
                        'currency': 'HKD',  # 明确标示这是港币
                        'conversion_rate': 1.0
                    }
                else:
                    self.logger.warning(f"获取账户 {acc_id} 资金信息失败: {data}")
                    return {'total_assets': 0.0, 'available_funds': 0.0, 'currency': 'HKD'}
                    
            finally:
                trd_ctx.close()
            
        except ImportError:
            self.logger.error("❌ 富途API包未安装，请运行: pip install futu-api")
            return {'total_assets': 0.0, 'available_funds': 0.0, 'currency': 'HKD'}
        except Exception as e:
            self.logger.error(f"获取账户资金失败: {e}")
            return {'total_assets': 0.0, 'available_funds': 0.0, 'currency': 'HKD'}
    
    def get_hkd_to_usd_rate(self) -> float:
        """获取港币到美元的汇率"""
        try:
            # 使用免费汇率API获取实时汇率
            response = requests.get(
                "https://api.exchangerate-api.com/v4/latest/HKD",
                timeout=5
            )
            if response.status_code == 200:
                data = response.json()
                usd_rate = data['rates'].get('USD', 0.128)  # 港币到美元汇率
                self.logger.info(f"✅ 获取实时汇率: 1 HKD = {usd_rate:.4f} USD")
                return usd_rate
            else:
                self.logger.warning("⚠️ 汇率API调用失败，使用默认汇率")
                return 0.128  # 默认汇率 1港币 ≈ 0.128美元
                
        except Exception as e:
            self.logger.warning(f"⚠️ 获取汇率失败: {e}，使用默认汇率")
            return 0.128  # 默认汇率
    
    def convert_hkd_to_usd(self, hkd_amount: float) -> float:
        """将港币金额转换为美元"""
        try:
            usd_rate = self.get_hkd_to_usd_rate()
            usd_amount = hkd_amount * usd_rate
            return usd_amount
        except Exception as e:
            self.logger.error(f"汇率转换失败: {e}")
            return hkd_amount * 0.128  # 使用默认汇率
    
    def get_all_brokers_accounts(self) -> List[Dict[str, Any]]:
        """获取所有券商的账户列表"""
        try:
            from futu import SecurityFirm
            
            # 支持的券商列表（使用真实存在的枚举值）
            brokers = [
                (SecurityFirm.FUTUSECURITIES, "FUTU HK"),
                (SecurityFirm.FUTUINC, "Moomoo US"),
            ]
            
            self.logger.info(f"准备获取 {len(brokers)} 个券商的账户信息")
            
            all_accounts = []
            
            for broker_enum, broker_name in brokers:
                try:
                    self.logger.info(f"🔄 获取 {broker_name} 券商账户...")
                    broker_accounts = self.get_broker_accounts(broker_enum, broker_name)
                    if broker_accounts:
                        all_accounts.extend(broker_accounts)
                        self.logger.info(f"✅ {broker_name}: 获取到 {len(broker_accounts)} 个账户")
                    else:
                        self.logger.info(f"ℹ️ {broker_name}: 无可用账户")
                        
                except Exception as e:
                    self.logger.warning(f"⚠️ 获取 {broker_name} 账户失败: {e}")
                    continue
            
            self.logger.info(f"✅ 总计获取到 {len(all_accounts)} 个可用账户")
            return all_accounts
            
        except Exception as e:
            self.logger.error(f"获取所有券商账户失败: {e}")
            return []
    
    def get_broker_accounts(self, broker_enum, broker_name: str) -> List[Dict[str, Any]]:
        """获取指定券商的账户列表"""
        try:
            from futu import OpenSecTradeContext, TrdEnv, TrdAccStatus, RET_OK, TrdMarket
            
            # 支持的市场列表
            markets = [
                (TrdMarket.US, "美股"),
                (TrdMarket.HK, "港股"),
                (TrdMarket.CN, "A股")
            ]
            
            all_broker_accounts = []
            seen_accounts = set()  # 用于去重
            
            # 遍历所有市场，获取该券商在各市场的账户
            for market_enum, market_name in markets:
                try:
                    # 创建交易连接 - 指定券商和市场
                    trd_ctx = OpenSecTradeContext(
                        filter_trdmarket=market_enum,
                        host='127.0.0.1', 
                        port=11111, 
                        security_firm=broker_enum
                    )
                    
                    try:
                        # 获取账户列表
                        ret, data = trd_ctx.get_acc_list()
                        if ret != RET_OK:
                            continue  # 该券商在此市场无账户，继续下一个市场
                        
                        # 过滤真实且可用的账户
                        for _, row in data.iterrows():
                            if row['trd_env'] == TrdEnv.REAL and row['acc_status'] == TrdAccStatus.ACTIVE:
                                acc_id = str(row['acc_id'])
                                
                                # 检查账户是否已经添加过（去重）
                                if acc_id in seen_accounts:
                                    continue
                                
                                # 获取账户资金信息
                                funds_info = self.get_account_funds_with_broker(acc_id, broker_enum, market_enum)
                                if funds_info['total_assets'] <= 0:  # 跳过无资产的账户
                                    continue
                                
                                # 根据券商类型处理货币
                                raw_assets = funds_info['total_assets']
                                raw_available = funds_info['available_funds']
                                
                                if broker_name == "FUTU HK":
                                    # FUTU HK：显示港币
                                    display_currency = "HKD"
                                    total_assets = raw_assets
                                    available_funds = raw_available
                                elif broker_name == "Moomoo US":
                                    # Moomoo US：显示美元
                                    display_currency = "USD"
                                    total_assets = raw_assets
                                    available_funds = raw_available
                                else:
                                    # 其他券商：根据市场判断（备用逻辑）
                                    if market_enum == TrdMarket.US:
                                        display_currency = "USD"
                                        total_assets = self.convert_hkd_to_usd(raw_assets)
                                        available_funds = self.convert_hkd_to_usd(raw_available)
                                    else:
                                        display_currency = "HKD"
                                        total_assets = raw_assets
                                        available_funds = raw_available
                                
                                account_info = {
                                    'acc_id': acc_id,
                                    'trd_env': 'REAL',
                                    'acc_type': str(row['acc_type']),
                                    'uni_card_num': str(row['uni_card_num']),
                                    'card_num': str(row['card_num']),
                                    'security_firm': broker_name,
                                    'security_firm_enum': broker_enum,
                                    'market': market_name,
                                    'market_enum': market_enum,
                                    'currency': display_currency,
                                    'acc_status': 'ACTIVE',
                                    'trdmarket_auth': row['trdmarket_auth'] if hasattr(row, 'trdmarket_auth') else [],
                                    'total_assets': total_assets,
                                    'available_funds': available_funds
                                }
                                
                                all_broker_accounts.append(account_info)
                                seen_accounts.add(acc_id)  # 标记为已添加
                                break  # 找到主要市场账户后，停止查找其他市场
                        
                    finally:
                        trd_ctx.close()
                        
                except Exception as e:
                    self.logger.debug(f"券商 {broker_name} 在 {market_name} 市场获取账户失败: {e}")
                    continue
            
            return all_broker_accounts
                
        except Exception as e:
            self.logger.warning(f"获取券商 {broker_name} 账户失败: {e}")
            return []
    
    def get_account_funds_with_broker(self, acc_id: str, broker_enum, market_enum) -> Dict[str, float]:
        """获取指定券商账户的资金信息，自动进行汇率转换"""
        try:
            from futu import OpenSecTradeContext, TrdEnv, RET_OK, TrdMarket
            
            # 创建交易连接
            trd_ctx = OpenSecTradeContext(
                filter_trdmarket=market_enum,
                host='127.0.0.1', 
                port=11111, 
                security_firm=broker_enum
            )
            
            try:
                # 查询账户资金信息
                ret, data = trd_ctx.accinfo_query(trd_env=TrdEnv.REAL, acc_id=int(acc_id))
                if ret == RET_OK and not data.empty:
                    row = data.iloc[0]
                    
                    # 获取原始港币金额
                    total_assets_hkd = float(row['total_assets'])
                    available_funds_hkd = float(row['avl_withdrawal_cash'])
                    
                    # 🔥 根据市场类型判断是否需要汇率转换
                    is_us_market = market_enum == TrdMarket.US
                    
                    if is_us_market:
                        # 美股市场：港币转换为美元
                        hkd_to_usd_rate = self.get_hkd_to_usd_rate()
                        total_assets = total_assets_hkd * hkd_to_usd_rate
                        available_funds = available_funds_hkd * hkd_to_usd_rate
                        
                        self.logger.info(f"💱 美股账户资金转换: HK${total_assets_hkd:,.2f} → ${total_assets:,.2f} USD (汇率: {hkd_to_usd_rate:.4f})")
                        
                        return {
                            'total_assets': total_assets,
                            'available_funds': available_funds,
                            'currency': 'USD',
                            'original_hkd_assets': total_assets_hkd,
                            'conversion_rate': hkd_to_usd_rate
                        }
                    else:
                        # 港股市场：直接使用港币
                        self.logger.info(f"💰 港股账户资金: HK${total_assets_hkd:,.2f}")
                        
                        return {
                            'total_assets': total_assets_hkd,
                            'available_funds': available_funds_hkd,
                            'currency': 'HKD',
                            'original_hkd_assets': total_assets_hkd,
                            'conversion_rate': 1.0
                        }
                else:
                    return {'total_assets': 0.0, 'available_funds': 0.0, 'currency': 'USD'}
                    
            finally:
                trd_ctx.close()
            
        except Exception as e:
            self.logger.error(f"获取账户资金失败: {e}")
            return {'total_assets': 0.0, 'available_funds': 0.0, 'currency': 'USD'}
    
    def get_available_brokers(self) -> List[Dict[str, Any]]:
        """获取用户真实拥有的券商列表"""
        try:
            from futu import SecurityFirm
            
            # 候选券商列表
            candidate_brokers = [
                (SecurityFirm.FUTUSECURITIES, "FUTU HK"),
                (SecurityFirm.FUTUINC, "Moomoo US"),
            ]
            
            available_brokers = []
            
            for broker_enum, broker_name in candidate_brokers:
                try:
                    # 尝试获取该券商的账户
                    broker_accounts = self.get_broker_accounts(broker_enum, broker_name)
                    if broker_accounts:  # 如果有账户，说明用户拥有此券商
                        broker_info = {
                            'broker_enum': broker_enum,
                            'broker_name': broker_name,
                            'account_count': len(broker_accounts),
                            'accounts': broker_accounts
                        }
                        available_brokers.append(broker_info)
                        self.logger.info(f"✅ 用户拥有券商: {broker_name} (账户数: {len(broker_accounts)})")
                    else:
                        self.logger.debug(f"ℹ️ 用户无券商: {broker_name}")
                        
                except Exception as e:
                    self.logger.debug(f"检查券商 {broker_name} 失败: {e}")
                    continue
            
            self.logger.info(f"✅ 用户总共拥有 {len(available_brokers)} 个券商")
            return available_brokers
            
        except Exception as e:
            self.logger.error(f"获取可用券商失败: {e}")
            return []
